#include <iostream>
#include <assert.h>
#include <cstring>

#include <tws_debugging.h>
#include "xinfomatdeletefiletypeparser.h"

std::string HTML_PATH = "/media/sd/html/";
std::string MOVIE_PATH = "/media/sd/movies/";

#define _DEBUGING_DELETE_FILE_

XInfomatDeleteFileTypeParser::XInfomatDeleteFileTypeParser()
	: m_result(INFOMAT_RESULT_OK),m_fileName(NULL)
{
}

XInfomatDeleteFileTypeParser::~XInfomatDeleteFileTypeParser()
{
}

void XInfomatDeleteFileTypeParser::getResource(QByteArray in_datagram)
{
	int headLength = sizeof(STInfomatConfigHead);
	char* data = new char[headLength];
	memcpy(data, in_datagram.data(), headLength);
	assert(INFOMAT_CONFIG_PROTOCOL == *data);

	STInfomatConfigHead * tmpdata = reinterpret_cast<STInfomatConfigHead*> (data);
	memcpy(&m_head, tmpdata, headLength);
	tmpdata = NULL; 

	char* fileName = new char[m_head.size];
	memcpy(fileName, in_datagram.data()+headLength, sizeof(m_head.size));
	m_fileName  = QString(fileName);
	fileName = NULL;

	/* clean up */
	if (NULL != fileName) {
		delete fileName;
		fileName = NULL;
	}

	if (NULL != data) {
		delete data ;
		data = NULL;
	}
#ifdef _DEBUGING_DELETE_FILE_
	DEBUG("delete file checking ...");
	DEBUG("Pass in Data, After Conversion");
	DEBUG("totoal data size:\t\t%d", in_datagram.size());
	DEBUG("protocol\t:%02x", m_head.protocol);
	DEBUG("type\t:%0d", m_head.type);
	DEBUG("size\t:%0d", m_head.size);
	DEBUG("result\t:%0d", m_head.result);
	DEBUG("command\t:%02d", m_head.command);
	DEBUG("file path\t:%s",m_fileName.toStdString().c_str());
#endif

	switch (m_head.command )
	{
	case INFOMAT_COMMAND_DELETE_HTML:
		deleteHtmlFile();
		break;

	case INFOMAT_COMMAND_DELETE_MOVIE:
		deleteMovieFile();
		break;

	default:
		DEBUG("XDeleteFile: no such command");
		m_result = INFOMAT_RESULT_ERR;
		break;
	}

	return;

}


QByteArray XInfomatDeleteFileTypeParser::getOutDatagram()
{
	m_head.result = m_result;
	
	char* data = reinterpret_cast<char*>(&m_head);
	QByteArray outData = QByteArray(data, sizeof(m_head));
	data = NULL;
	return outData;
}


void XInfomatDeleteFileTypeParser::deleteHtmlFile()
{
	std::string htmlFile;
	htmlFile.append(HTML_PATH);
	htmlFile.append(m_fileName.toStdString().c_str());

	FILE* pFile = fopen(htmlFile.c_str(), "r");
	if (NULL == pFile)
	{
		m_result = INFOMAT_RESULT_ERR;
		return;
	}

	int ret = remove(htmlFile.c_str());
	if( 0!=ret )
	{
		DEBUG("remove %s [fail]",htmlFile.c_str());
		m_result = INFOMAT_RESULT_ERR;
	}

	return ;
}


void XInfomatDeleteFileTypeParser::deleteMovieFile()
{
	std::string movieFile;
	movieFile.append(MOVIE_PATH);
	movieFile.append(m_fileName.toStdString().c_str());

	FILE* pFile = fopen(movieFile.c_str(), "r");
	if (NULL == pFile)
	{
		m_result = INFOMAT_RESULT_ERR;
		DEBUG("file:%s does not exist", movieFile.c_str());
		return;
	}

	int ret = remove(movieFile.c_str());
	if( 0!=ret )
	{
		DEBUG("remove %s [fail]",movieFile.c_str());
		m_result = INFOMAT_RESULT_ERR;
		return;
	}

	return ;
}
